<template>
  <div style="display: flex;flex-direction: column;gap: 10px">
    <t-row class="card">
      <t-col v-for="(item,index) in panelList" :key="index" :span="3">
        <div class="header">
          <div class="title">{{ item.title }}</div>
        </div>
        <div class="header">
          <t-link v-if="item.path" @click="toPath(item)" :style="{ fontSize: `36px`}" theme="primary" hover="color">{{
              item.number
            }}
          </t-link>
          <div v-else :style="{ fontSize: `36px`}">{{ item.number }}</div>
        </div>
      </t-col>
    </t-row>
    <t-row :gutter="[16, 16]">
      <t-col v-if="site_tag === 'jtt'" :xs="12" :xl="4">
        <t-card title="计划类别" class="dashboard-chart-card">
          <chart-view @click="(data)=>{clickToIndex(data,'projectCategory')}" :chartOption="chartOpt2"
                      :autoResize="false" height="326px"/>
        </t-card>
      </t-col>
      <t-col :xs="12" :xl="site_tag === 'jtt'?4:6">
        <t-card title="学科分类" class="dashboard-chart-card">
          <chart-view @click="(data)=>{clickToIndex(data,'subjectClassification')}" :chartOption="chartOpt"
                      :autoResize="false" height="326px"/>
        </t-card>
      </t-col>
      <t-col :xs="12" :xl="site_tag === 'jtt'?4:6">
        <t-card title="项目类型" class="dashboard-chart-card">
          <chart-view @click="(data)=>{clickToIndex(data,'projectType')}" :chartOption="chartOpt3" :autoResize="false"
                      height="326px"/>
        </t-card>
      </t-col>
    </t-row>
    <t-row :gutter="[16, 16]">
      <t-col :xs="12" :xl="6">
        <t-card title="年度项目总数" class="dashboard-chart-card">
          <t-tabs :defaultValue="1" @change="(val)=>{ getMapByYear(val) }">
            <t-tab-panel :value="index+1" v-for="(item,index) in phaseTabs" :key="index" :label="item.name">
              <chart-view :chartOption="chartOpt4"
                          @click="(data)=>{clickLineToIndex(data,'declareYear', item.statusList)}"
                          :autoResize="false" height="326px"/>
            </t-tab-panel>
          </t-tabs>
        </t-card>
      </t-col>
      <t-col :xs="12" :xl="6">
        <t-card title="年度经费总和" class="dashboard-chart-card">
          <t-tabs :defaultValue="1" @change="(val)=>{ getAllFunding(val) }">
            <t-tab-panel :value="index+1" v-for="(item,index) in phaseTabs" :key="index" :label="item.name">
              <chart-view :chartOption="chartOpt5" :autoResize="false" height="326px"/>
            </t-tab-panel>
          </t-tabs>
        </t-card>
      </t-col>
    </t-row>
    <t-row align="stretch" :gutter="[16, 16]">
      <t-col :xs="12" :xl="6">
        <t-card title="单位申报排名" class="dashboard-rank-card">
          <t-table hover :data="deptRankData" :columns="deptRankColumns" rowKey="departmentId">
            <template #id="{ rowIndex }">
            <span :class="getRankClass(rowIndex)">
              {{ rowIndex + 1 }}
            </span>
            </template>
            <template #projectCount="{ row }">
              <a @click="clickDeptToIndex({data:{
                lableValue: row.deptName
              }}, 'declareDeptName')">{{ row.projectCount }}</a>
            </template>
          </t-table>
        </t-card>
      </t-col>
      <t-col :xs="12" :xl="6">
        <t-card title="最新申报项目" class="dashboard-rank-card">
          <t-table hover :data="projectData" :columns="projectColumns" rowKey="id">
            <template #projectName="{ row }">
              <t-link v-if="row.version === '2024'"
                      @click="dialog.objId=row.id;dialog.header=row.projectName;dialog.open_project_detail=true"
                      hover="color" theme="primary">{{ row.projectName }}
              </t-link>
              <t-link v-else @click="dialog.objId=row.id;dialog.header=row.projectName;dialog.open_project_detail=true"
                      hover="color" theme="primary">{{ row.projectName }}
              </t-link>
            </template>
            <template #subjectClassification="{ row }">
              {{ row.subjectClassification | filterByDict(dict.type.subject_classification) }}
            </template>
            <template #projectType="{ row }">
              {{ row.projectType | filterByDict(dict.type.project_type) }}
            </template>
            <template #op="{ row }">
              <t-button v-if="row.version === '2024'" size="small"
                        @click="dialog.objId=row.id;dialog.header=row.projectName;dialog.open_project_detail=true"
                        variant="text" class="t-button-link">
                <t-icon name="info-circle" slot="icon"/>
                详情
              </t-button>
              <t-button v-else size="small"
                        @click="dialog.objId=row.id;dialog.header=row.projectName;dialog.open_project_detail=true"
                        variant="text" class="t-button-link">
                <t-icon name="info-circle" slot="icon"/>
                详情
              </t-button>
            </template>
            <template #dateRange="{ row }">
              {{ row.startDate }}-{{ row.endDate }}
            </template>
            <template #projectStatus="{ row }">
              <t-tag @click="dialog.header=row.projectName;dialog.objId=row.id;dialog.open_approve_list=true"
                     class="cursor-pointer" :theme="handleTheme(row.projectStatus, dict.type.project_status)"
                     variant="light">
                {{ row.projectStatus | filterByDict(dict.type.project_status) }}
              </t-tag>
            </template>
          </t-table>
        </t-card>
      </t-col>
    </t-row>
    <project-detail-dialog :header="dialog.header" :objId="dialog.objId" :visible.sync="dialog.open_project_detail"
                           v-if="dialog.open_project_detail"></project-detail-dialog>
    <item-detail-dialog :header="dialog.header" :objId="dialog.objId" :visible.sync="dialog.open_item_detail"
                        v-if="dialog.open_item_detail"></item-detail-dialog>
    <approve-list :header="dialog.header" :objId="dialog.objId" :visible.sync="dialog.open_approve_list"
                  v-if="dialog.open_approve_list"></approve-list>
  </div>
</template>

<script lang="jsx">
import ApproveList from "./approve/components/approve-list.vue";
import ProjectDetailDialog from "./pm/components/project-detail-dialog.vue";
import ItemDetailDialog from "./pm/components/item-detail-dialog.vue";

export default {
  name: "home",
  dicts: ["project_type", "subject_classification", "sys_user_sex", "prof_tit", "degree", "duty", "platform_type", "member_type", "project_status"],
  components: {
    ApproveList,
    ProjectDetailDialog,
    ItemDetailDialog
  },
  data() {
    return {
      site_tag: import.meta.env.VITE_SITE_TAG,
      phaseTabs: [
        {
          name: "立项",
          statusList: ["9", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34"]
        },
        {
          name: "大纲",
          statusList: ["18", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34"]
        },
        {
          name: "合同",
          statusList: ["22", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34"]
        },
        {
          name: "验收",
          statusList: ["29", "31", "32", "33", "34"]
        },
      ],
      resizeTime: 1,
      currentMonth: "",
      chartOpt: {},
      chartOpt2: {},
      chartOpt3: {},
      chartOpt4: {},
      chartOpt5: {},
      dialog: {
        open_project_detail: false,
        open_approve_list: false,
        header: "",
        objId: 0,
        open_item_detail: false,
      },
      panelList: [],
      deptRankData: [],
      deptRankColumns: [
        {
          colKey: "id",
          title: "排行",
          align: "center",
        },
        {
          colKey: "deptName",
          title: "单位名称",
          align: "center",
          width: 180
        },
        {
          colKey: "projectCount",
          title: "申报项目个数",
          align: "center",
        },
      ],
      projectData: [],
      projectColumns: [
        // {
        //   colKey: "id",
        //   title: "项目编号",
        //   align: "center",
        //   ellipsis: true
        // },
        {
          colKey: "projectName",
          title: "项目名称",
          align: "center",
          ellipsis: (h, {row}) => <div>{row.projectName}</div>,
          ellipsisTitle: false,
          width: 300,
        },
        {
          colKey: 'declareDeptName',
          title: '申报单位',
          align: 'center',
          width: 180
        },
        {
          colKey: 'declareDate',
          title: '申报日期',
          align: 'center',
          width: 120
        },
        // {
        //   colKey: "projectLeaderName",
        //   title: "项目负责人",
        //   align: "center",
        //   ellipsis: true
        // },
        // {
        //   colKey: "projectCategoryName",
        //   title: "计划类别",
        //   align: "center",
        //   ellipsis: true
        // },
        // {
        //   colKey: "subjectClassification",
        //   title: "学科分类",
        //   align: "center",
        //   ellipsis: true
        // },
        // {
        //   colKey: "projectType",
        //   title: "项目类型",
        //   align: "center",
        //   ellipsis: true
        // },
        // {
        //   colKey: "startDate",
        //   title: "开始时间",
        //   align: "center",
        //   ellipsis: true
        // },
        // {
        //   colKey: "endDate",
        //   title: "结束时间",
        //   align: "center",
        //   ellipsis: true
        // },
        // {
        //   colKey: "declareDeptName",
        //   title: "承担单位",
        //   align: "center",
        //   ellipsis: true
        // },
        {
          colKey: "projectStatus",
          title: "项目状态",
          align: "center",
          width: 220,
        },
      ],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectCategory: '',
        projectName: '',
        projectType: '',
        subjectClassification: '',
        dateRange: []
      },
    }
  },
  created() {
    this.getProjectList();
    this.getAllSubjectClassification();
    this.getAllProjectCategory();
    this.getAllProjectType();
    this.getAllCount();
    this.getMapByYear(1);
    this.getAllFunding(1);
    this.getDeptProjectRanking();
  },
  methods: {
    clickDeptToIndex(data, param) {
      const query = {}
      query[param] = data.data.lableValue;
      query["projectStatuss"] = ["9", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34"];
      this.$router.push({
        path: '/kjxm/pm/project-index',
        query
      })
    },
    clickToIndex(data, param) {
      const query = {}
      query[param] = data.data.lableValue
      this.$router.push({
        path: '/kjxm/pm/project-index',
        query
      })
    },
    clickLineToIndex(data, param, statusList) {
      const query = {}
      query[param] = data.name
      query["projectStatuss"] = statusList;
      this.$router.push({
        path: '/kjxm/pm/project-index',
        query
      })
    },
    toPath(item) {
      this.$router.push({
        path: item.path,
        query: item.query
      });
    },
    getRankClass(index) {
      return ['dashboard-rank__cell', {'dashboard-rank__cell--top': index < 3}];
    },
    getDeptProjectRanking() {
      this.$api.kjxm.home.getDeptProjectRanking(this.queryParams).then(response => {
        this.deptRankData = response.rows;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getMapByYear(phase) {
      this.$api.kjxm.home.getMapByYear(phase).then(response => {
        this.chartOpt4 = this.$eChartFn.getLineChart(Object.keys(response.data), Object.values(response.data));
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getAllFunding(type) {
      this.$api.kjxm.home.getMoneyMapByYear(type).then(response => {
        let legendData = ['经费总额', '集团补总额']
        if (this.site_tag === 'jtt') {
          legendData = ['经费总额', '厅补总额']
        }
        const xdata = Object.keys(response.data)
        const seriesData1 = []
        const seriesData2 = []
        Object.keys(response.data).forEach(key => {
          seriesData1.push(response.data[key].adviceFunding)
          seriesData2.push(response.data[key].subsidyFunding)
        })
        this.chartOpt5 = this.$eChartFn.getBarChart2(xdata, {
          tooltip: {
            trigger: 'axis',
            formatter(params) {
              let relVal = params[0].name;
              let i = 0;
              const l = params.length;
              for (; i < l; i++) {
                relVal += `<br/>${params[i].marker}${params[i].seriesName} : ${params[i].value.toLocaleString()}万元`;
              }
              return relVal;
            }
          },
          title: {
            // title为标题部分，有一级标题text，二级标题subtext。这里我们使用二级标题，再修改一下这个二级标题的位置即可出现我们想要的效果了，当然样式也可以通过title.subtextStyle去配置
            subtext: "单位(万元)",
            left: 10,// 距离左边位置
            top: 16,// 距离上面位置
            // subtextStyle:{ // 设置二级标题的样式
            //   color:"#baf"
            // }
          },
          legend: {
            data: legendData
          },
          series: [
            {
              name: legendData[0],
              type: 'bar',
              data: seriesData1,
              label: {
                show: true,
                position: 'top',
                formatter(d) {
                  return `${d.data}`;
                },
              },
            },
            {
              name: legendData[1],
              type: 'bar',
              data: seriesData2,
              label: {
                show: true,
                position: 'top',
                formatter(d) {
                  return `${d.data}`;
                },
              },
            }
          ]
        });
      }).catch((e) => {
        this.$message.error(e.toString());
      });

    },
    getAllCount() {
      Promise.all([this.$api.kjxm.home.getMyProjectCount(), this.$api.kjxm.home.getMyDeptProjectCount(),
        this.$api.kjxm.home.getMyApproveProjectCount(), this.$api.kjxm.home.getMyApprovedProjectCount(), this.$api.kjxm.home.getProjectCountInPhase(), this.$api.kjxm.home.getProjectReviewCount()]).then(response => {
        if (this.$store.state.user.roles.includes("kjcspy") || this.$store.state.user.permissions.includes("*:*:*")) {
          this.panelList = [
            // {
            //   title: '我的项目',
            //   number: response[0].data.count,
            //   path: '/kjxm/pm/project-my',
            // },
            {
              title: '项目总数',
              number: response[1].data.count,
              path: '/kjxm/pm/project-index',
              query: {
                projectStatuss: ['2', '3', '4', '5', '8', '9', '14', '15', '17', '18', '19', '21', '22', '24', '25', '27', '28', '29', '34']
              }
            },
            // {
            //   title: '待我审批项目',
            //   number: response[2].data.count,
            //   path: '/kjxm/approve/approve-my',
            // },
            {
              title: '申报阶段',
              number: response[4].data.lxCount,
              path: '/kjxm/apply/project-index',
              query: {
                projectStatuss: ['2']
              }
            },
            {
              title: '形式审查阶段',
              number: response[5].data.count,
              path: '/kjxm/approve/approve-project',
              query: {}
            },
            {
              title: '专家盲审阶段',
              number: response[4].data.zjmsCount,
              path: '/kjxm/zjms/project-index',
              query: {
                projectStatuss: ['8', '5']
              }
            },
            {
              title: '大纲阶段',
              number: response[4].data.dgCount,
              path: '/kjxm/outline/project-index',
              query: {
                projectStatuss: ['9', '14', '17', '15', '19']
              }
            },
            // {
            //   title: '大纲评审阶段',
            //   number: response[4].data.dgpsCount,
            //   path: '/kjxm/outline/project-index',
            //   query: {
            //     projectStatuss: ['17', '15', '19']
            //   }
            // },
            {
              title: '任务书阶段',
              number: response[4].data.htCount,
              path: '/kjxm/contract/project-index',
              query: {
                projectStatuss: ['18', '21']
              }
            },
            {
              title: '在研阶段',
              number: response[4].data.yssqCount,
              path: '/kjxm/acceptance/project-index',
              query: {
                projectStatuss: ['22', '24']
              }
            },
            {
              title: '验收评审阶段',
              number: response[4].data.yspsCount,
              path: '/kjxm/acceptance/project-index',
              query: {
                projectStatuss: ['27', '25', '29', '28']
              }
            },
            {
              title: '已结题总数',
              number: response[4].data.ysCount,
              path: '/kjxm/acceptance/project-accepted-index',
              query: {
                projectStatuss: ['34']
              }
            },
          ]
        } else {
          this.panelList = [
            // {
            //   title: '我的项目',
            //   number: response[0].data.count,
            //   path: '/kjxm/pm/project-my',
            // },
            {
              title: '项目总数',
              number: response[1].data.count,
              path: '/kjxm/pm/project-index',
              query: {
                projectStatuss: ['2', '3', '4', '5', '8', '9', '14', '15', '17', '18', '19', '21', '22', '24', '25', '27', '28', '29', '34']
              }
            },
            {
              title: '待我审批项目',
              number: response[2].data.count,
              path: '/kjxm/approve/approve-my',
            },
            {
              title: '申报阶段',
              number: response[4].data.lxCount,
              path: '/kjxm/apply/project-index',
              query: {
                projectStatuss: ['2']
              }
            },
            {
              title: '形式审查阶段',
              number: response[5].data.count,
              path: '/kjxm/pm/project-index',
              query: {
                projectStatuss: ['3', '4']
              }
            },
            {
              title: '专家盲审阶段',
              number: response[4].data.zjmsCount,
              path: '',
              query: {
                projectStatuss: ['8', '5']
              }
            },
            {
              title: '大纲阶段',
              number: response[4].data.dgCount,
              path: '/kjxm/outline/project-index',
              query: {
                projectStatuss: ['9', '14', '17', '15', '19']
              }
            },
            // {
            //   title: '大纲评审阶段',
            //   number: response[4].data.dgpsCount,
            //   path: '/kjxm/outline/project-index',
            //   query: {
            //     projectStatuss: ['17', '15', '19']
            //   }
            // },
            {
              title: '任务书阶段',
              number: response[4].data.htCount,
              path: '/kjxm/contract/project-index',
              query: {
                projectStatuss: ['18', '21']
              }
            },
            {
              title: '在研阶段',
              number: response[4].data.yssqCount,
              path: '/kjxm/acceptance/project-index',
              query: {
                projectStatuss: ['22', '24']
              }
            },
            {
              title: '验收评审阶段',
              number: response[4].data.yspsCount,
              path: '/kjxm/acceptance/project-index',
              query: {
                projectStatuss: ['27', '25', '29', '28']
              }
            },
            {
              title: '已结题总数',
              number: response[4].data.ysCount,
              path: '/kjxm/acceptance/project-accepted-index',
              query: {
                projectStatuss: ['34']
              }
            },
          ]
        }

      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getAllProjectType() {
      this.$api.kjxm.home.getAllProjectType().then(response => {
        const data = [];
        response.data.forEach(val => {
          data.push({
            ...val,
            name: val.label
          })
        })
        this.chartOpt3 = this.$eChartFn.getPieChart(data);
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getAllSubjectClassification() {
      this.$api.kjxm.home.getAllSubjectClassification().then(response => {
        const data = [];
        response.data.forEach(val => {
          data.push({
            ...val,
            name: val.label
          })
        })
        this.chartOpt = this.$eChartFn.getPieChart(data);
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getAllProjectCategory() {
      this.$api.kjxm.home.getAllProjectCategory().then(response => {
        const data = [];
        response.data.forEach(val => {
          data.push({
            ...val,
            name: val.label
          })
        })
        this.chartOpt2 = this.$eChartFn.getPieChart(data);
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getProjectList() {
      this.$api.kjxm.project.list(this.queryParams).then(response => {
        this.projectData = response.rows;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
  }
}
</script>

<style lang="less" scoped>
.card {
  border: 1px solid var(--td-component-border);
  border-radius: var(--td-radius-medium);
  background-color: var(--td-bg-color-container);
  padding: 10px 10px;

  .header {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    padding: 10px 10px;
    position: relative;

    .title {
      font: var(--td-font-title-medium);
      color: var(--td-text-color-primary);
      margin-right: var(--td-comp-margin-l);
      word-break: break-all;
    }
  }
}

@import '@/style/variables.less';
.dashboard-rank-card {
  height: 100%;
}

.dashboard-rank__cell {
  display: inline-flex;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  color: white;
  font-size: 14px;
  background-color: @gray-color-5;
  align-items: center;
  justify-content: center;
  font-weight: 700;

  &--top {
    background: @brand-color;
  }
}
</style>
